
package com.gemframework.modules.prekit.sys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gemframework.common.annotation.ApiLog;
import com.gemframework.common.annotation.ApiSign;
import com.gemframework.common.annotation.ApiToken;
import com.gemframework.common.utils.GemValidateUtils;
import com.gemframework.model.common.BaseResultData;
import com.gemframework.model.common.SaltPassword;
import com.gemframework.model.entity.po.Agent;
import com.gemframework.model.entity.po.Member;
import com.gemframework.model.enums.ExceptionCode;
import com.gemframework.modules.prekit.sys.entity.request.MemberSetPasswordRequest;
import com.gemframework.service.AgentService;
import com.gemframework.service.MemberService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.gemframework.common.utils.security.GemPasswordUtils.saltPassword;

@RestController
@CrossOrigin
public class MemberApi {

	@Resource
	private MemberService memberService;
    @Resource
    private AgentService agentService;

	@ApiLog(name = "修改密码")
	@PostMapping("setPassword")
	@ApiSign
	@ApiToken
	public BaseResultData setPassword(MemberSetPasswordRequest request) {
		//参数校验器
		GemValidateUtils.GemValidate(request);
		memberService.setPassword(request.getMemberId(),request.getPassword());
		return BaseResultData.SUCCESS();
	}

	@PostMapping("register")
	public BaseResultData register(@RequestBody Member member){
	    if(member.getCodes()!=null&&!"".equals(member.getCodes())){
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("code",member.getCodes());
            Agent one = agentService.getOne(queryWrapper1);
            member.setAgentId(Integer.parseInt(one.getId().toString()));
        }
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("account",member.getAccount());
		Member one = memberService.getOne(queryWrapper);
		if(one==null){
			SaltPassword saltPassword = saltPassword(member.getPassword());
			member.setPassword(saltPassword.getPassword());
			member.setSalt(saltPassword.getSalt());
			return BaseResultData.SUCCESS(memberService.save(member));
		}
		return BaseResultData.ERROR(ExceptionCode.USER_EXIST);
	}

}
